package com.yksj.healthtalk.ui.server;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.TrolleyAdapter;
import com.yksj.healthtalk.adapter.TrolleyAdapter.TrolleyListLisenter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.ShopPayActivity;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.ShopListItemEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.StringFormatUtils;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 购物车
 * @author Administrator
 * 
 * {
    "money": 282.4,
    "detail": [
        {
            "SHELVES_FLAG": 1,
            "PICTURE_ADDR": "http://img.yaofang.cn/images0/70/5a/3e/705a3e3f96bb2f95f2b9a8aa6b7131b02d0cbb61.jpg",
            "VIP_PRICE": 268,
            "FACTORY": "Miktec Intemational,Inc",
            "GOODS_NAME": "针叶樱桃胶囊",
            "GOODS_ID": 1016930,
            "SHOP_PRICE": 298,
            "SPECIFICATIONS": "60粒",
            "GOODS_COUNT": 1
        },
        {
            "SHELVES_FLAG": 1,
            "PICTURE_ADDR": "",
            "VIP_PRICE": 14.4,
            "FACTORY": "杭州天橙日化有限公司",
            "GOODS_NAME": "象爱修护润泽膏",
            "GOODS_ID": 1004304,
            "SHOP_PRICE": 16,
            "SPECIFICATIONS": "40ml",
            "GOODS_COUNT": 1
        }
    ],
    "CUSTOMER_ACCOUNTS": "3089547",
    "count": 2,
    "CART_	ID": 200087,
    "askInfo": {
        "addr": "http://m.yaofang.cn/cart/getJKLGoodsList",
        "username": "3089547",
        "customerID": 115565,
        "cartID": 200087,
        "sec": "524537*f898de26dca9fe971e05486fca15a9c7",
        "askTime": "20140107144744",
        "merchantID": 2
    },
    "INSERT_TIME": "20140107144740"
}
 * 
 */
public class ServerCenterTrolleyActivity extends BaseFragmentActivity implements
		OnClickListener, OnDilaogClickListener, TrolleyListLisenter,
		OnItemClickListener {

	private PullToRefreshListView mPullToRefreshListView;
	private ListView mListView;
	private Button mSettleBtn;
	private TrolleyAdapter adapter;
	private ArrayList<ShopListItemEntity> entities;
	private String mTotalMoney;
	private String mTotalCount;
	private int position = -1;// 列表的索引值
	private TextView mGoodMessageTv;
	private ClickSure mDefault = ClickSure.defaut;
	private String detail;
	private ArrayList<Integer> initializeCount;
	private String merchantId;
	private JSONObject object;
	private String response;
	private String ShopPayUrl;
	private String isSpecialFlag;
	// [
	// {
	// "PICTURE_ADDR":
	// "http://img.yaofang.cn/images0/58/fc/4c/58fc4cffc6639355d0591ffd794228729033bd18.jpg",
	// "VIP_PRICE": 38,
	// "FACTORY": "烟台四维高科生化有限公司",
	// "GOODS_NAME": "塞呋盾天然复合胶乳高阻隔安全套",
	// "GOODS_ID": 100553,
	// "SHOP_PRICE": 0,
	// "SPECIFICATIONS": "2片青柠檬光面",
	// "GOODS_COUNT": 1
	// }
	// ]
	@Override
	protected void onCreate(Bundle arg0) { 
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.server_center_trolley);

		initWidget();
		initData();
	}

	enum ClickSure {
		DeleteAll(1), defaut(0), DeleteOne(2);
		ClickSure(int i) {
			value = i;
		}

		int value;
	}

	void setClickSure(ClickSure sure) {
		mDefault = sure;
	}

	private void initData() {
		initializeCount.clear();
		entities.clear();
		if(response != null){
			try {
				object = new JSONObject(response);
				if (object.has("money")) {
					mTotalMoney = object.getString("money");
					mTotalCount = object.getString("count");
					//判断特殊商品
					isSpecialFlag = object.getString("specialFlag");
					detail = object.getString("detail");
					entities.addAll((ArrayList<ShopListItemEntity>) JsonParseUtils.getGsonToTrolleyList(detail));
					for (int i = 0; i < entities.size(); i++) {
						initializeCount.add(entities.get(i).getGOODS_COUNT());
					}
					initView();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else {//没购买任何服务
			initView();
			return;
		}

		adapter = new TrolleyAdapter(this, entities);
		mListView.setAdapter(adapter);
	}

	/**
	 * 刷新界面
	 */
	private void initView() {
		if (entities == null || entities.size() == 0) {
			mSettleBtn.setBackgroundColor(Color.GRAY);
			mGoodMessageTv.setText("购物车内暂时没有商品");
			titleRightBtn2.setVisibility(View.GONE);
		} else {
			mSettleBtn.setBackgroundColor(getResources().getColor(R.color.text_orange));
			mGoodMessageTv.setText("共有" + mTotalCount + "件商品" + "\n" + "总额:￥"
					+ mTotalMoney);
			titleRightBtn2.setVisibility(View.VISIBLE);
		}
	}

	private void initWidget() {
		// TODO Auto-generated method stub
		initTitle();
		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		mSettleBtn = (Button) findViewById(R.id.settle_btn);
		mGoodMessageTv = (TextView) findViewById(R.id.goods_message_tv);

		titleTextV.setText(R.string.shopping_trolley);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setText("清空购物车");
		titleRightBtn2.setTextColor(getResources().getColor(R.color.text_blue));

		titleLeftBtn.setOnClickListener(this);
		titleRightBtn2.setOnClickListener(this);
		mSettleBtn.setOnClickListener(this);
		mListView.setOnItemClickListener(this);
		
		initializeCount = new ArrayList<Integer>();
		entities = new ArrayList<ShopListItemEntity>();
		Intent intent = getIntent();
		merchantId = intent.getExtras().getString("MERCHANT_ID");
		if (intent.hasExtra("response")) {
			response = intent.getStringExtra("response");
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.title_right2:
			setClickSure(ClickSure.DeleteAll);
			DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(), "你确定要清除购物车吗?",getString(R.string.cancel), getString(R.string.sure), this);
			break;
		case R.id.settle_btn:
			// 跳转到药房网
			if (object == null || entities ==null || entities.size() == 0) {
				return;
			}
			Boolean isDrop = true;
			//查看商品是否全部下架
			for (int i = 0; i < entities.size(); i++) {
				if (!entities.get(i).getSHELVES_FLAG().equals("0")) {
					isDrop = false;
				}
			}
			
			if(isDrop){
				SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), "购物车中为下架商品");
				return;
			}
			ArrayList<HashMap<String, Integer>> value = new ArrayList<HashMap<String,Integer>>();
			for (int i = 0; i < entities.size(); i++) {
				if (!entities.get(i).getSHELVES_FLAG().equals("0")) {
					HashMap<String, Integer> map = new HashMap<String, Integer>();
					map.put("goods_id", Integer.valueOf(entities.get(i).getGOODS_ID()));
					map.put("goods_number", entities.get(i).getGOODS_COUNT());
					value.add(map);
				}
			}
			try {
			ShopPayUrl = HttpRestClient.doHttpShopPay(com.alibaba.fastjson.JSONArray.toJSONString(value), object.optString("CART_ID"), merchantId, SmartFoxClient.getLoginUserId(), object.getJSONObject("askInfo"),null);
			//特殊商品
			if (!isSpecialFlag.equals("")) {
				DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(), isSpecialFlag, "取消", "确定", this);
			}else {
				HttpRestClient.doHttpTimeStep(merchantId, "10");
				Intent intent = new Intent(getApplicationContext(), ShopPayActivity.class);
				intent.putExtra("merchantId", merchantId);
				intent.putExtra("url",ShopPayUrl );
				intent.putExtra("addr", object.getJSONObject("askInfo").optString("addr"));
				startActivityForResult(intent, 1);
			}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case R.id.delete:
			setClickSure(ClickSure.DeleteOne);
			if (v.getTag() != null && v.getTag() instanceof Integer) {
				position = (Integer) v.getTag();
			}
			DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(), "确定从购物车删除该商品?",getString(R.string.cancel), getString(R.string.sure), this);
			break;
		default:
			break;
		}
	}

	@Override
	public void onDismiss(DialogFragment fragment) {
	}

	@Override
	public void onClick(DialogFragment fragment, View v) {
		if (mDefault == ClickSure.DeleteOne) {
			if (position != -1) {
				HttpRestClient.doHttpAddCart(StringFormatUtils.getDeleteGoodsInfoStr(entities.get(position)),entities.get(position).getMERCHANT_ID(),new AsyncHandler(position));
			}
		} else if (mDefault == ClickSure.DeleteAll) {
			HttpRestClient.doHttpClearCartList(merchantId,new AsyncHandler(-1));
		}else {
			try {
				HttpRestClient.doHttpTimeStep(merchantId, "10");
				Intent intent = new Intent(getApplicationContext(), ShopPayActivity.class);
				intent.putExtra("merchantId", merchantId);
				intent.putExtra("url",ShopPayUrl );
				intent.putExtra("addr", object.getJSONObject("askInfo").optString("addr"));
				startActivityForResult(intent, 1);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	@Override
	public void addCount(int position, ShopListItemEntity entity,
			int beforeChangeCount, int endChangeCount) {
		// TODO Auto-generated method stub
		mTotalMoney  = add(Float.valueOf(mTotalMoney), Float.valueOf(entity
				.getVIP_PRICE()))+"";
		mTotalCount = (Integer.valueOf(mTotalCount) + 1) + "";
		initView();
	}

	@Override
	public void onBackPressed() {
		// 判断购物车的内容是否被修改
		if (entities.size() == 0) { 
			HTalkApplication.haveShoppingCar = 0;
		}else {
			HTalkApplication.haveShoppingCar = 1;
		}
		boolean isChange = false;
		if (!TextUtils.isEmpty(detail)) {
			if (initializeCount.size() != 0 && initializeCount.size() == entities.size()) {
				for (int i = 0; i < entities.size(); i++) {
					if (initializeCount.get(i) != entities
							.get(i).getGOODS_COUNT()) {
						isChange = true;
					}
				}
				if (isChange) {
					isChange();
				} else {
					finish();
				}
			}else {
				finish();
			}
		}else {
			finish();
		}
	}

	private void isChange() {
		DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(), 
				"是否保存购物车列表的内容", "取消", "确定", new OnDilaogClickListener() {

					@Override
					public void onDismiss(DialogFragment fragment) {
						finish();
					}

					@Override
					public void onClick(DialogFragment fragment, View v) {
						com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
						ArrayList<HashMap<String, Integer>> value = new ArrayList<HashMap<String,Integer>>(); 
						for (int i = 0; i < entities.size(); i++) {
							HashMap<String, Integer> map = new HashMap<String, Integer>();
							map.put("goods_id", Integer.valueOf(entities.get(i).getGOODS_ID()));
							map.put("goods_number", entities.get(i).getGOODS_COUNT());
							value.add(map);
						}
						object.put("flag", 1);
						object.put("goods", com.alibaba.fastjson.JSONArray.toJSONString(value));
						HttpRestClient.doHttpAddCart(object.toString(), merchantId, null);
						finish();
					}
				});
	}

	@Override
	public void minusCount(int position, ShopListItemEntity entity,
			int beforeChangeCount, int endChangeCount) {
		if (beforeChangeCount != 1) {
			mTotalMoney = sub(Float.valueOf(mTotalMoney), Float.valueOf(entity
					.getVIP_PRICE()))+"";
			mTotalCount = (Integer.valueOf(mTotalCount) - 1) + "";
			initView();
		}
	}

	class AsyncHandler extends JsonHttpResponseHandler {
		private int position;
		
		public AsyncHandler(int position) {
			super(ServerCenterTrolleyActivity.this);
			this.position = position;
		}

		@Override
		public void onSuccess(int statusCode, JSONObject response) {
			if (response.has("info")) {
				try {
					String info = response.getString("info");
					String code = response.getString("code");
					if (code.equals("0")) {
						if (mDefault == ClickSure.DeleteOne) {
							if (position != -1) {
								entities.remove(position);
							}
						} else if (mDefault == ClickSure.DeleteAll) {
							entities.clear();
						}
						float sum = 0;
						int count = 0;
						for (int i = 0; i < entities.size(); i++) {
							count = count+entities.get(i).getGOODS_COUNT();
							sum = add(sum, mul(Float.valueOf(entities.get(i).getVIP_PRICE()),Float.valueOf(entities.get(i).getGOODS_COUNT())));
						}
						mTotalMoney = sum+"";
						mTotalCount = count+"";
						adapter.notifyDataSetChanged();
						initView();
					}
					ToastUtil.showShort(getApplicationContext(), info);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			super.onSuccess(statusCode, response);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg2>=1 && arg2 <= entities.size()) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), ServerCenterDescription.class);
			ShopListItemEntity entity = entities.get(arg2 - 1);
			entity.setMERCHANT_ID(merchantId);
			intent.putExtra("entity",entity );
			startActivity(intent);
		}
	}
	
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		//返回刷新界面
		if (arg0 == 1 && arg1 == RESULT_OK) {
			HttpRestClient.doHttpCartList(merchantId,new JsonHttpResponseHandler(this){
				
				@Override
				public void onSuccess(int statusCode, JSONArray response) {
					super.onSuccess(statusCode, response);
				}
				@Override
				public void onSuccess(int statusCode, JSONObject res) {
					if (res.has("info")) {
						try {
							ToastUtil.showToastPanl(res.getString("info"));
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} else if (res.has("money")) {
						response = res.toString();
						initData();
//						{}
					}else {
						response = null;
						initData();
					}
					super.onSuccess(statusCode, response);
				}
				
				
				@Override
				public void onFailure(Throwable error, String content) {
					ToastUtil.showShort(getApplicationContext(), error.toString());
					super.onFailure(error, content);
				}
				
			});
		}
		super.onActivityResult(arg0, arg1, arg2);
	}
	
    /**
     * 提供精确的加法运算。
     * @param v1 被加数
     * @param v2 加数
     * @return 两个参数的和
     */
    public static Float add(Float v1,Float v2){
        BigDecimal b1 = new BigDecimal(Float.toString(v1));
        BigDecimal b2 = new BigDecimal(Float.toString(v2));
        return b1.add(b2).floatValue();
    }
    
    /**
     * 提供精确的减法运算。
     * @param v1 被减数
     * @param v2 减数
     * @return 两个参数的差
     */
    public static Float sub(Float v1,Float v2){
        BigDecimal b1 = new BigDecimal(Float.toString(v1));
        BigDecimal b2 = new BigDecimal(Float.toString(v2));
        return b1.subtract(b2).floatValue();
    }

    public float mul(float v1,float v2){//乘法
        BigDecimal b1 = new BigDecimal(Float.toString(v1));
        BigDecimal b2 = new BigDecimal(Float.toString(v2));
       return b1.multiply(b2).floatValue();
       }
}
